package com.gx.mvp.net;

import android.util.Log;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by Guoxin on 2019-12-07.
 */

public class ApiManager {

    /**
     * 正式环境
     */
    //public static final String BASE_URL = "https://www.baidu.com/";

    /**
     * 测试环境
     */
    public static final String BASE_URL = "https://www.baidu.com/";

    // 读取超时时间为15秒
    public static final int READ_TIME_OUT = 15;

    // 连接超时时间为15秒
    public static final int CONNECT_TIME_OUT = 15;

    private Retrofit     mRetrofit;         // Retrofit实例
    private OkHttpClient mOkHttpClient;     // OkHttpClient实例
    private ApiService   mApiService;       // api接口

    /**
     * 单例
     */
    public static ApiManager getInstance() {
        return ApiManagerHolder.mInstance;
    }

    private static class ApiManagerHolder {
        private static ApiManager mInstance = new ApiManager();
    }

    /**
     * 构造方法
     */
    private ApiManager() {
        this.init();
    }

    /**
     * 初始化
     */
    private void init() {
        this.initOkHttp();
        this.initRetrofit();
        this.initApiService();
    }

    /**
     * 初始化OkHttp
     */
    private void initOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        // 打印请求log日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("okHttp", "OkHttp:　" + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 添加日志拦截器
        builder.addInterceptor(loggingInterceptor);

        // 支持重试
        builder.retryOnConnectionFailure(true);
        // 自定义重试次数
        builder.addInterceptor(new RetryIntercepter(1));
        builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS); // 设置连接超时
        builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS); // 设置读取超时
        builder.writeTimeout(READ_TIME_OUT, TimeUnit.SECONDS);  // 设置写入超时
        this.mOkHttpClient = builder.build();
    }

    /**
     * 初始化Retrofit
     */
    private void initRetrofit() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(BASE_URL);
        builder.client(this.mOkHttpClient);
        builder.addConverterFactory(ResponseConverterFactory.create());
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        this.mRetrofit = builder.build();
    }

    /**
     * 初始化Api
     */
    private void initApiService() {
        this.mApiService = mRetrofit.create(ApiService.class);
    }

    /**
     * 获取ApiService
     */
    public ApiService getApiService() {
        return mApiService;
    }

    /**
     * 重试拦截器
     */
    public class RetryIntercepter implements Interceptor {

        public  int maxRetry;//最大重试次数
        private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

        public RetryIntercepter(int maxRetry) {
            this.maxRetry = maxRetry;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            while (!response.isSuccessful() && retryNum < maxRetry) {
                retryNum++;
                response = chain.proceed(request);
            }
            return response;
        }
    }
}
